﻿using Microsoft.SharePoint;
using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Linq;

namespace Portal
{
    [ToolboxItemAttribute(false)]
    public partial class TipsTricks : WebPart
    {
        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
        // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public TipsTricks()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Web;
            SPList tipList = web.GetList("/Lists/TipsTricks/");

            SPQuery tipQuery = new SPQuery();

            tipQuery.Query = @"<OrderBy>
                             <FieldRef Name='Modified' Ascending='False' />
                            </OrderBy>";
            tipQuery.ViewFields = @"       <FieldRef Name='ID'/>
                                            <FieldRef Name='Title'/>
                                            <FieldRef Name='ShortDescription'/>                                            
                                                                             
                                ";
            tipQuery.RowLimit = 2;

            SPListItemCollection tipItems = tipList.GetItems(tipQuery);

            if (tipItems.Count > 0)
            {
                var tipsItemsModified = from tipItem in tipItems.GetDataTable().AsEnumerable()
                                          select new
                                          {
                                              TipTitle = tipItem["Title"].ToString(),
                                              TipShortDescription = tipItem["ShortDescription"].ToString().Length >= 200 ? tipItem["ShortDescription"].ToString().Substring(0, 200) + "..." : tipItem["ShortDescription"].ToString()
                                             
                                          };

                lstTip.DataSource = tipsItemsModified.ToList();
                lstTip.DataBind();
            }
        }
    }
}
